#include "ByteBuffer.h"
#include <fstream>

ByteBuffer::ByteBuffer(const char* path)
	:curRead(0)
{
	this->initWithFile(path);
}

bool ByteBuffer::initWithFile(const char* path)
{
	using namespace std;
	ifstream file;
	file.open(path, ios::binary|ios::in);
	if (file.good())
	{
		std::streamoff len = 0;
		std::streampos start = file.tellg();
		file.seekg(0, std::ios::end);
		std::streampos end = file.tellg();
		file.seekg(0, std::ios::beg);
		len = end - start;
		this->buffer.resize((size_t)len);
		this->curRead = 0;
		file.read(reinterpret_cast<char*>(this->buffer.data()), len);
		file.clear();
		file.close();
		return true;
	}
	file.clear();
	file.close();
	return false;
}


size_t ByteBuffer::read(byte* buf, size_t len)
{
	size_t readLen = len;
	if (this->curRead + len > this->buffer.size())
	{
		readLen = this->buffer.size() - this->curRead;
	}
	if (readLen > 0)
	{
		memcpy(buf, this->buffer.data()+this->curRead, readLen);
		this->curRead += readLen;
	}

	return readLen;
}